﻿using System.Collections.Generic;
using System.Net.Http.Json;
using System.Security.Cryptography;

namespace OnlineOpinionAnalysis.Client.Services
{
    public class BiliVideoService : IBiliVideoService
    {
        private HttpClient _httpClient;
        public List<BiliVideo> BiliVideos { get; set; }
        public Dictionary<int, List<BiliVideo>> TidVideos { get; set; } = new();
		public Dictionary<int, List<BiliVideo>> MasterTidVideos { get; set; } = new();


		public BiliVideoService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<List<BiliVideo>> GetBiliVideos(int number = 100)
        {
            var result = await _httpClient.GetFromJsonAsync<List<BiliVideo>>($"api/bilivideo?number={number}");
            
            BiliVideos = result??new();
            if (BiliVideos.Count > 0)
            {
                foreach (var video in BiliVideos)
                {
                    if (TidVideos.ContainsKey(video.Tid))
                    {
                        TidVideos[video.Tid].Add(video);
                    }
                    else
                    {
						TidVideos.Add(video.Tid,new(){ video });
					}

                    int masterTid=TidHelper.GetTidMaster(video.Tid);
					if (MasterTidVideos.ContainsKey(masterTid))
					{
						MasterTidVideos[masterTid].Add(video);
					}
					else
					{
						MasterTidVideos.Add(masterTid, new() { video });
					}
				}
            }

            return result ?? new();
        }

        public async Task<List<BiliVideo>> GetBiliVideosByTid(int tid, int number = 100)
        {
            List<BiliVideo> result;
            if (BiliVideos.Count > 0)
            {
                result = BiliVideos.Where(video=>video.Tid==tid).ToList();
            }
            else
            {
                result = await _httpClient.GetFromJsonAsync<List<BiliVideo>>($"api/bilivideo/{tid}?number={number}");
            }
           
            return result ?? new();
        }

        public async Task<int> GetVideoCount()
        {
            var result = await _httpClient.GetFromJsonAsync<int>($"api/bilivideo/count");
            return result;
        }
    }
}
